
import { createKnowledgeList, delKnowledgeList, getKnowledgeDrawerList, getKnowledgeList, publishOrDrafs, updateKnowledgeList } from '@/service';
import { IKnowledgeDrawerList, IKnowledgeList } from '@/types';
import { Effect, Reducer } from 'umi';

export interface KnowledgeModelState {
  knowledgeList: IKnowledgeList[],
  knowledgeLength: number,
  KnowledgeDrawerFile:IKnowledgeDrawerList[],
  KnowledgeDrawerFileLength:number
}

export interface KnowledgeModelType {
  namespace: 'knowledge';
  state: KnowledgeModelState;
  effects: {
    getKnowledgeList: Effect;
    delKnowledgeList: Effect;
    publishOrDrafs: Effect;
    getKnowledgeDrawerList: Effect;
    createKnowledgeList: Effect;
    updateKnowledgeList: Effect;
  };
  reducers: {
    save: Reducer<KnowledgeModelState>;
  };
}

const KnowledgeModel: KnowledgeModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'knowledge',

  // 数据模型状态，相当于vuex的state
  state: {
    knowledgeList: [],
    knowledgeLength: 0,
    KnowledgeDrawerFile:[],
    KnowledgeDrawerFileLength:0
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    // 获取
    *getKnowledgeList({ payload }, { call, put }) {

      let res = yield call(getKnowledgeList, payload);
      if (res.data) {
        yield put({
          type: 'save',
          payload: {
            knowledgeList: res.data[0],
            knowledgeLength: res.data[1]
          }
        })
      }
    },
    // 删除
    *delKnowledgeList({ payload }, { call, put }) {
      let res = yield call(delKnowledgeList, payload);

    },
    // 设为草稿或发布上线
    *publishOrDrafs({payload},{call,put}){
        const res = yield call(publishOrDrafs,payload);      
    },
    // 获取第二个抽屉图片列表数据
    *getKnowledgeDrawerList({payload},{call,put}){
      const res = yield call(getKnowledgeDrawerList,payload);
      if(res.data){
        yield put({
          type:'save',
          payload:{
            KnowledgeDrawerFile : res.data[0],
            KnowledgeDrawerFileLength : res.data[1]
          }
        })
      }
    },
    // 创建知识小册
    *createKnowledgeList({payload},{call,put}){
      const res = yield call (createKnowledgeList,payload);      
    },
    // 更新知识小册
    *updateKnowledgeList({payload},{call,put}){
      const res = yield call ( updateKnowledgeList ,payload);      
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default KnowledgeModel;
